/* eslint-disable no-multi-spaces */
/* eslint-disable jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions, max-len */
import React, {
  useState, useEffect, useMemo, useCallback,
} from 'react';
import {
  Table, Tooltip, Button,
} from 'choerodon-ui/pro';
import { Avatar, message, Popover } from 'choerodon-ui';
import {
  Page, Action, Header, Breadcrumb, Content, HeaderButtons, useFormatMessage, Choerodon, axios,
} from '@choerodon/master';
import { useHistory, useLocation } from 'react-router';
import { observer } from 'mobx-react-lite';
import { ColumnAlign } from 'choerodon-ui/pro/lib/table/enum';
import { Modal } from '@choerodon/master/lib/components/modal';
import UserInfo from '@/components/userInfo';
import StatusTag from './components/StatusTag';
import { useTableStore } from './stores';
import {
  stopRecord, startRecord, deleteRecord, executeRecord,
} from './service';

import './index.less';
import PopoverContent, { PopoverHeader } from './components/personalTokenPopover';
import useGetPersonalToken from '../../hooks/useGetPersonalToken';

const { Column } = Table;
interface Iprops{

}

const Index:React.FC<Iprops> = (props:Iprops) => {
  const {
    intlPrefix,
    prefixCls,
    tableDs,
    dyTableStore,
    projectId,
    formatMessage,
  } = useTableStore();
  const format = useFormatMessage('c7ncd.continuous.deployment.table.operate');
  useEffect(() => {

  }, []);
  const history = useHistory();
  const locations = useLocation();
  const {
    search,
    pathname,
  } = locations;

  const [personalToken, setPersonalToken] = useGetPersonalToken(projectId);
  const [toolTip, setToolTop] = useState(false);
  const handleTokenReset = (t:string) => {
    setPersonalToken(t);
  };

  // 头部按钮
  const getHeaderButtons = () => {
    const res = [
      {
        name: formatMessage({ id: `${intlPrefix}.createModel` }),
        icon: 'cloud_done-o',
        permissions: ['choerodon.code.project.deploy.continuous-deployment.ps.create'],
        display: true,
        handler: () => openCreateModel(),
      },
      {
        display: true,
        element: (
          <Popover
            content={() => (
              <PopoverContent personalToken={personalToken} handleTokenReset={handleTokenReset} projectId={projectId} />
            )}
            title={PopoverHeader}
            trigger="click"
            overlayClassName="c7ncd-continuousDeployment-token-popover"
          >
            <Button icon="password">个人令牌</Button>
          </Popover>
        ),
      },
      {
        icon: 'refresh',
        display: true,
        handler: () => refresh(),
      },
    ];
    return <HeaderButtons items={res} showClassName={false} />;
  };

  const handleOpenTokenModal = () => {

  };

  // 刷新
  const refresh = () => {
    tableDs.query();
  };

  /**
   * 以下是操作函数逻辑
   */

  // 创建持续部署流程
  const openCreateModel = () => {
    history.push({
      pathname: '/devops/continuous-deployment/operation/create',
      search: `${search}&personalToken=${personalToken}`,
    });
  };
  // 点击名称跳转到详情页
  const handleOnclick = (record:any) => {
    const id = record.get('id');
    return () => {
      history.push({
        pathname: `/devops/continuous-deployment/detail/${id}`,
        search,
      });
    };
  };
  // 执行
  const handleExecute = async (record:any) => {
    try {
      const res = await executeRecord(projectId, record.get('id'));
      if (res) {
        refresh();
      }
    } catch (e) {
      Choerodon.handleResponseError(e);
    }
  };
  // 停用的回调
  const handleStop = (record:any) => {
    Modal.open({
      key: Modal.key(),
      title: '停用部署流程',
      children: '确定停用该条部署流程吗？',
      movable: false,
      okText: '停用',
      // @ts-ignore
      onOk: async () => {
        try {
          const res = await stopRecord(projectId, record.get('id'));
          if (res) {
            refresh();
            message.success('停用成功');
          }
        } catch (e) {
          Choerodon.handleResponseError(e);
        }
      },
    });
  };
  // 启用的回调
  const handleStart = (record:any) => {
    Modal.open({
      key: Modal.key(),
      title: '启用部署流程',
      children: '确定启用该条部署流程吗？',
      movable: false,
      okText: '启用',
      // @ts-ignore
      onOk: async () => {
        try {
          const res = await startRecord(projectId, record.get('id'));
          if (res) {
            refresh();
            message.success('启用成功');
          }
        } catch (e) {
          Choerodon.handleResponseError(e);
        }
      },
    });
  };
  // 删除的回调
  const handleDelete = (record:any) => {
    Modal.open({
      key: Modal.key(),
      title: '删除部署流程',
      children: '确定删除该条部署流程吗？',
      movable: false,
      okText: '删除',
      // @ts-ignore
      onOk: async () => {
        try {
          const res = await deleteRecord(projectId, record.get('id'));
          if (res) {
            refresh();
            message.success('删除成功');
          }
        } catch (e) {
          Choerodon.handleResponseError(e);
        }
      },
    });
  };

  /**
   * 以下是渲染模块逻辑
   *
   */

  // 渲染三点操作 根据状态显示相对应的操作
  const renderAction = useCallback(({ record, value, text }:any) => {
    let actionData:object[] = [];
    if (record.get('enable') === false) {
      record.get('status') === 'running'
        ? actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.enable'],
            text: format({ id: 'start' }),
            action: () => handleStart(record),
          },
        ]
        : actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.enable'],
            text: format({ id: 'start' }),
            action: () => handleStart(record),
          },
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.delete'],
            text: format({ id: 'delete' }),
            action: () => handleDelete(record),
          },
        ];
    }
    if (record.get('enable') === true) {
      record.get('status') === 'running'
        ? actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.execute'],
            text: format({ id: 'operate' }),
            action: () => handleExecute(record),
          },
        ]
        : actionData = [
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.execute'],
            text: format({ id: 'operate' }),
            action: () => handleExecute(record),
          },
          {
            service: ['choerodon.code.project.deploy.continuous-deployment.ps.disable'],
            text: format({ id: 'stop' }),
            action: () => handleStop(record),
          },
        ];
    }
    return <Action data={actionData} />;
  }, []);
  // 渲染部署流程名称
  const renderName = ({ record, value }:any) => (
    <span
      className={`${prefixCls}-content-column-name`}
      onClick={handleOnclick(record)}
    >
      {value || ''}
    </span>
  );
  // 渲染最近运行状态
  const renderRunStatus = ({ record, value }:any) => (
    <StatusTag status={value} size={12} className={`${prefixCls}-content-column-runStatus`} />
  );
  // 渲染运行阶段
  const renderStage = ({ record }:any) => {
    const stageRecords = record?.get('stageRecordList')?.slice();
    const type = record.get('triggerType');
    return (
      <>
        <div className={`${prefixCls}-content-column-stage`} style={getStyle() as any}>
          <Tooltip title={getTitle(stageRecords)} placement="top">
            {stageRecords && stageRecords.map(({ name }:any, index:number) => (
              <span className={`${prefixCls}-content-column-stage-name`}>
                {name}
                &nbsp;&nbsp;
              </span>

            ))}
          </Tooltip>
        </div>
        <div className={`${prefixCls}-content-column-stage`} style={getStyle() as any}>
          {stageRecords && stageRecords.map(({ name, status }:any, index:number) => (
            <>
              <span className={`${prefixCls}-content-column-stage-line  ${prefixCls}-content-column-stage-line-${type}`} />
              <span className={`${prefixCls}-content-column-stage-item ${prefixCls}-content-column-stage-item-${status}`} />
            </>
          ))}
        </div>
      </>
    );
  };
  // 渲染触发信息
  const renderTrigger = ({ record, value }:any) => {
    const type = record.get('triggerType');
    // 使用地图存储触发信息类型
    const map = new Map([
      ['manual', '手动触发'],
      ['schedule', '定时触发'],
      ['app_version', '应用服务版本触发'],
      ['api', 'api触发'],
    ]);
    if (value || type) {
      return (
        <div className={`${prefixCls}-content-column-trigger`}>
          <UserInfo name={value?.realName} avatar={value?.imageUrl} id={value?.email} />
          <div className={`${prefixCls}-content-column-trigger-type`}>
            <Tooltip
              title={map.get(type)}
            >
              { type && map.get(type)}
            </Tooltip>
          </div>
        </div>
      );
    }
    return '';
  };
  // 渲染启用禁用状态
  const renderEnable = ({ record, value }:any) => <StatusTag status={value} size={12} />;
  // 自定义运行阶段样式
  const getStyle = () => ({
    overflow: 'hidden',
    textOverflow: 'ellipsis',
    whiteSpace: 'nowrap',
  });
  // title提示
  const getTitle = (stageRecords:any) => {
    const arr:string[] = [];
    stageRecords && stageRecords.map((item:any, index:number) => {
      if (index === stageRecords.length - 1) {
        return  arr.push(item.name);
      }
      return arr.push(`${item.name}-`);
    });
    return arr;
  };
  // 渲染时间
  const getStyles = () => ({
    whiteSpace: 'nowrap',
    overflow: 'hidden',
    textOverflow: 'ellipsis',
  });
  return (
    <Page>
      <Header>
        {getHeaderButtons()}
      </Header>
      <Breadcrumb  />
      <Content>
        <Table dataSet={tableDs} className={`${prefixCls}-content`} rowHeight="auto">
          <Column name="name" renderer={renderName} align={'left' as ColumnAlign} style={getStyles() as any} />
          <Column renderer={renderAction} width={60} />
          <Column name="status" renderer={renderRunStatus} align={'left' as ColumnAlign} />
          <Column name="stageRecordList" renderer={renderStage} align={'left' as ColumnAlign} style={getStyle() as any} />
          <Column name="trigger" renderer={renderTrigger} align={'left' as ColumnAlign} />
          <Column name="startedDate" align={'left' as ColumnAlign} title={formatMessage({ id: `${intlPrefix}.staredDates` })} tooltip={'overflow' as any} style={getStyles() as any} />
          <Column name="enable" renderer={renderEnable} align={'left' as ColumnAlign} width={120} />
        </Table>
      </Content>
    </Page>
  );
};
export default observer(Index);
